/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.manager.controler;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.asiainfo.ability.base.service.EsUtilsBean;
import org.asiainfo.ability.base.service.TraceService;
import org.asiainfo.ability.base.utils.JsonUtils;
import org.asiainfo.ability.base.utils.StringUtils;
import org.asiainfo.ability.manager.vo.SearchCondition;
import org.asiainfo.ability.manager.vo.Throughput;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: visen
 * @Date: 2018/1/16
 * @Description:
 */
@RestController
@RequestMapping(value = "/monitor")
public class MonitorControler {
    public static final Logger logger = LogManager.getLogger(MonitorControler.class);


    @Autowired
    private TraceService traceService;


    @RequestMapping(value = "/service/{serviceName}", method = RequestMethod.GET)
    public @ResponseBody
    String computeThroughput(@PathVariable String serviceName, HttpServletRequest request
            , HttpServletResponse response) throws Exception {
        Map conditions = new HashMap();
        conditions.put("serviceid", serviceName);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        Date time = new Date(System.currentTimeMillis());
        long begin = time.getTime();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.MINUTE, -1);
        String timeFiled = "begintime";
        long end = calendar.getTime().getTime();
        conditions.put(timeFiled, QueryBuilders
                .rangeQuery(timeFiled)
                .from(end)
                .to(begin));
        List<Map> result = null;
        List<String> fetchSources = new ArrayList();
        fetchSources.add("state");
        fetchSources.add("costtime");
        result = traceService.search("record_db", "record", conditions, null, null);
        Throughput throughput = new Throughput();
        int len = result.size();
        double done = 0, totalTime = 0;
        Map item = null;
        for (int i = 0; i < len; i++) {
            int costtime = ((Integer) (result.get(i)).get("costtime")).intValue();
            if (costtime > 0) {
                totalTime += costtime;
                done++;
            }
        }
        DecimalFormat df = new DecimalFormat("#####0.009");
        if(done>0) {
            throughput.setQps(df.format(done / 60));
            throughput.setAvg(df.format(totalTime/(done*1000)));
            throughput.setReq(String.valueOf(len));
        }

        return JsonUtils.toJSON(throughput);
    }


    private void setRet(HttpServletResponse response, String code) {
        try {
            response.getWriter().write(code);
        } catch (IOException e) {
            logger.error("", e);
        }
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        Date time = new Date(1518691239111L);
        System.out.println((sf).parse("2018-02-15 18:40:39 999").getTime());
        long begin = time.getTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.MINUTE, -1);
        System.out.println(sf.format(calendar.getTime()));

    }


}
